import 'dart:convert';

import 'package:get/get.dart';
import 'package:psi/utils/utils.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../entity/response/login_resp.dart';

class SpKey {
  static const token = 'token';
  static const currentUser = 'currentUser';

}

/// 本地存储
class SharePreferenceService extends GetxService {
  late SharedPreferences _sharedPreferences;

  Future<SharePreferenceService> init() async {
    _sharedPreferences = await SharedPreferences.getInstance();
    return this;
  }

  SharedPreferences get sharedPreferences => _sharedPreferences;

  static SharePreferenceService get to => Get.find();

  static void saveToken(String? token) {
    if (token == null) {
      return;
    }
    to._sharedPreferences.setString(SpKey.token, token);
  }

  static void removeToken() {
    to._sharedPreferences.remove(SpKey.token);
  }

  static String? getToken() {
    return to._sharedPreferences.getString(SpKey.token);
  }

  static void saveStr(String str, String key) {
    to._sharedPreferences.setString(key, str);
  }

  static String? getStr(String key) {
    return to._sharedPreferences.getString(key);
  }

  static SharedPreferences sp() => to._sharedPreferences;

  static User? getUser() {
    String? userJson = to._sharedPreferences.getString(SpKey.currentUser);
    if (userJson == null || userJson.isEmpty) {
      return null;
    }
    User user = User.fromJson(json.decode(userJson));
    return user;
  }

  static void saveUser(User? user) async {
    if (user == null) {
      return;
    }
    String encode = json.encode(user);
    await to._sharedPreferences.setString(SpKey.currentUser, encode);
  }

  static void removeUser() {
    to._sharedPreferences.remove(SpKey.currentUser);
  }

}
